package com.tuanzi.loan.web.bean.family.sms;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.sms.SmsUserDefinition;
import com.tuanzi.loan.business.service.sms.SmsUserDefinitionService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.util.GsonUtils;
import com.tuanzi.loan.vo.request.family.SmsUserDefinitionRequest;
import com.tuanzi.loan.web.configuration.JSFInfoBean;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class SmsUserDefinitionBean extends JSFInfoBean<SmsUserDefinitionRequest> {

	@Autowired
	private SmsUserDefinitionService smsUserDefinitionService;

	private List<SmsUserDefinition> smsUserDefinitions;
	private SmsUserDefinition smsUserDefinition;
	private Long selectedSmsUserDefinitionId;

	@PostConstruct
	private void init() {
		$ = new SmsUserDefinitionRequest();
		smsUserDefinition = new SmsUserDefinition();
		smsUserDefinitions = smsUserDefinitionService.findAll();
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(SMS_ELIMINATE_BLACK_LIST, SMS_ELIMINATE_ACTIVITY, USER_LABEL_PROFESSION);
	}

	public void onReset() {
		smsUserDefinition = new SmsUserDefinition();
		smsUserDefinition.setId(selectedSmsUserDefinitionId);
		$ = new SmsUserDefinitionRequest();
	}

	public void onSelectSmsUserDefinition() {
		if (selectedSmsUserDefinitionId == null) {
			$ = new SmsUserDefinitionRequest();
			smsUserDefinition = new SmsUserDefinition();
		} else {
			smsUserDefinition = smsUserDefinitions.stream().filter(x -> x.getId().equals(selectedSmsUserDefinitionId)).findFirst().get();
			$ = GsonUtils.toObject(smsUserDefinition.getContent(), SmsUserDefinitionRequest.class);
		}
	}

	public Boolean editing() {
		return smsUserDefinition.getId() != null;
	}

	public void onSave() {
		if (StringUtils.isBlank(smsUserDefinition.getName())) {
			addErrorMessage("必须输入定义名称");
			return;
		}
		smsUserDefinition.setContent(GsonUtils.toJson($));
		smsUserDefinition.setId(selectedSmsUserDefinitionId);
		smsUserDefinitionService.saveOrUpdate(smsUserDefinition);
		selectedSmsUserDefinitionId = smsUserDefinition.getId();
		smsUserDefinitions = smsUserDefinitionService.findAll();
		addSuccessfullyMessage();
	}

}
